package au.com.handsunited.utils;

import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Encrypter {

	private static Logger logger = LoggerFactory.getLogger(Encrypter.class);

    public static final String HEX_DIGITS = "0123456789ABCDEF";

    private static byte[] getBytes(String str) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        StringTokenizer st = new StringTokenizer(str, "-", false);
        while (st.hasMoreTokens()) {
            int i = Integer.parseInt(st.nextToken());
            bos.write((byte) i);
        }
        return bos.toByteArray();
    }

    private static String getString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            sb.append(hexDigits(b));
        }
        return sb.toString();
    }

    public static String hexDigits(int num) {
        int p0 = num & 0xF;
        int p1 = (num & 0xF0) >> 4;
        return "" + HEX_DIGITS.charAt(p1) + HEX_DIGITS.charAt(p0);
    }

    public static String sha(String source) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            byte[] bytes = md.digest(source.getBytes());
            return getString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
